package com.yunfeng.supercall.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.lin.activity.LauncherActivity;
import com.lin.activity.SuperFriendsNearByActivity;
import com.lin.fragments.ExploreFragment;
import com.lin.fragments.MineFragment;
import com.lin.fragments.RecentCallFragment;
import com.lin.fragments.SuperFriendsFragment;
import com.lin.utils.Session;
import com.lin.utils.Session.ResultReceiver;
import com.lin.utils.Session.SignupResult;
import com.ly.quickdev.library.activity.BaseFragmentTabActivity;
import com.ly.quickdev.library.adapter.ListBaseAdapter.ViewHolder;
import com.ly.quickdev.library.utils.JsonUtils;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.update.UmengUpdateAgent;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.bean.AdsBean;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.LevelBean;
import com.yunfeng.supercall.bean.LevelColorBean;
import com.yunfeng.supercall.bean.MyCircleBean;
import com.yunfeng.supercall.bean.ShareConfigBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.fragment.RecentChatListFragment;
import com.yunfeng.supercall.fragment.ShareFragment;
import com.yunfeng.supercall.fragment.SuperContactsFragment;
import com.yunfeng.supercall.httputils.HttpClient;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.iface.MessageAccessable;
import com.yunfeng.supercall.manager.CommentCountManager;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;
import com.yunfeng.supercall.service.CallConnectionService;
import com.yunfeng.supercall.service.CallConnectionService.MyBinder;

/**
 * 主页面，管理5个Fragment
 * 
 * @author 洋
 * 
 */
public class CopyOfMainActivity extends BaseFragmentTabActivity {

	/** 存放 */
	public static final Map<String, String> LEVEL_MAPS = new HashMap<String, String>();
	public static final Map<String, LevelColorBean> LEVEL_COLOR_MAPS = new HashMap<String, LevelColorBean>();
	private MessageReceiver mMessageReceiver;
	private String[] mTabTitles;
	Session mSession;
	UserBean userbean;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mTabTitles = getResources().getStringArray(R.array.tab_titles);
		super.onCreate(savedInstanceState);
		mSession = Session.getSession();
		mSession.init(getApplicationContext(), true);
		
		userbean = BaseActivity.getUser(getApplicationContext());
		
		/** 查询友盟更新 */
		UmengUpdateAgent.update(this);
		findViewById(R.id.tab_container).setBackgroundResource(
				R.drawable.tab_line_top);
		/** 注册聊天消息监听器 */
		mMessageReceiver = new MessageReceiver();
		IntentFilter mIntentFilter = new IntentFilter();
		mIntentFilter.addAction(Constants.ACTION_RECEIVE_MSG);
		registerReceiver(mMessageReceiver, mIntentFilter);
		/** 加载一系列数据 */
		loadMyCircle();
		loadShareConfig();
		loadLevels();
		loadLevelColors();
		loadAds();

		/** 开启极光推送 */
		JPushInterface.setLatestNotificationNumber(getApplicationContext(), 3);
		JPushInterface.resumePush(getApplicationContext());
		try {
			JPushInterface.setAlias(this, BaseActivity.getUser(getActivity())
					.getPhone(), new TagAliasCallback() {

				@Override
				public void gotResult(int arg0, String arg1, Set<String> arg2) {
					// TODO Auto-generated method stub

				}
			});
		} catch(NullPointerException e) {
			e.printStackTrace();
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			finish();	
		}
		signIn();
		
		/** 绑定到聊天服务商 */
		bindService(new Intent(this, CallConnectionService.class),
				mServiceConnection, Service.BIND_AUTO_CREATE);
		
		
	/*	startActivity(new Intent(this,
				SuperFriendsNearByActivity.class));*/
	}


	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// if (mCallConnectionService != null) {
		// mCallConnectionService.setShowNotification(false);
		// }
		NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		manager.cancelAll();
		loadShareCommentCount();

		boolean has = SuperFriendsManager.hasNewFriend(this);
		mImageViewFriendRedDot.setVisibility(has ? View.VISIBLE
				: View.INVISIBLE);
	}
	
	protected void onPause() {
		super.onPause();
		// if (mCallConnectionService != null) {
		// mCallConnectionService.setShowNotification(true);
		// }
	};

	
	private CallConnectionService mCallConnectionService;
	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			mCallConnectionService = ((MyBinder) service).getService();
			mCallConnectionService.setShowNotification(false);
		}
	};

	
	private void loadAds() {
		// TODO Auto-generated method stub
		mSession.getSysAd(getApplicationContext(),userbean.getUserid(), new ResultReceiver<ArrayList<AdsBean>>() {

			@Override
			public void onResult(boolean last, ArrayList<AdsBean> mAds) {
				// TODO Auto-generated method stub
				ManagerFactory.createManager(AdsBean.class).saveList(mAds);
			}
			
		});

	}

	HttpClient mHttpClient = new HttpClient();
	public int mCommentCount;

	private void loadShareCommentCount() {
		final int count = CommentCountManager.getInstance(getActivity())
				.getMaxId();
		JSONObject json = BaseActivity.getBaseParams(getActivity());
		try {
			json.put("i_maxid", count);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(Constants.FUNCTION_GET_MY_SHARE_COMMENT_COUNT, json,
				new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				try {
					JSONObject json = new JSONObject(data.substring(1,
							data.length() - 1));
					mCommentCount = json.getInt("num");
					int max = json.getInt("maxid");
					Fragment fragment = getSupportFragmentManager()
							.findFragmentByTag(mTabTitles[4]);
					if (fragment != null
							&& fragment instanceof MessageAccessable) {
						((MessageAccessable) fragment).refreshMessage();
					}
					CommentCountManager.getInstance(getActivity())
					.setMaxId(max);
					CommentCountManager.getInstance(getActivity())
					.setCurrentId(count);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	/** 记录登陆信息（登陆天数） */
	private void signIn() {
		
		mSession.loginLog(getApplicationContext(), userbean.getUserid(), "android", new ResultReceiver<SignupResult>() {

			@Override
			public void onResult(boolean last, SignupResult args) {
				// TODO Auto-generated method stub
				
			}
			
		});

	}





	public void onBackPressed() {
		moveTaskToBack(false);
		// Intent i = new Intent();
		// i.addCategory(Intent.CATEGORY_HOME);
		// i.setAction(Intent.ACTION_MAIN);
		// startActivity(i);
	};

	/** 加载等级对应的字体颜色 */
	private void loadLevelColors() {
		mSession.getSuColorList(getApplicationContext(),userbean.getUserid(), new ResultReceiver<ArrayList<LevelColorBean>>() {

			@Override
			public void onResult(boolean last, ArrayList<LevelColorBean> mLevels) {
				// TODO Auto-generated method stub
				ManagerFactory.createManager(LevelColorBean.class)
				.saveList(mLevels);
				LEVEL_COLOR_MAPS.clear();
				for (LevelColorBean level : mLevels) {
					LEVEL_COLOR_MAPS.put(level.getId() + "", level);
				}
			}
			
		});
	}

	/**
	 * 加载等级信息
	 */
	private void loadLevels() {
		
		mSession.getLevelList(getApplicationContext(), userbean.getUserid(), 0, new ResultReceiver<ArrayList<LevelBean>>() {

			@Override
			public void onResult(boolean last, ArrayList<LevelBean> mLevels) {
				// TODO Auto-generated method stub
				ManagerFactory.createManager(LevelBean.class).saveList(mLevels);
				LEVEL_MAPS.clear();
				for (LevelBean level : mLevels) {
					LEVEL_MAPS.put(level.getLevelid() + "",
							level.getLevelname());
				}
			}
			
		});
	}

	/**
	 * 加载分享的内容
	 */
	private void loadShareConfig() {
		JSONObject json = BaseActivity.getBaseParams(getActivity());
		HttpClient mHttpClient = new HttpClient();
		mHttpClient.post(Constants.FUNCTION_SHARE_CONFIG, json,
				new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onReceiveData(String data, String msg) {
				// TODO Auto-generated method stub
				ShareConfigBean.sConfig = JsonUtils.parse(
						data.substring(1, data.length() - 1),
						ShareConfigBean.class);
			}
		});
	}

	/**
	 * 加载我的圈子
	 */
	private void loadMyCircle() {
		
		mSession.getQuanziList(getApplicationContext(), userbean.getUserid(), 0, new ResultReceiver<ArrayList<MyCircleBean>> () {

			@Override
			public void onResult(boolean last, ArrayList<MyCircleBean> circles) {
				// TODO Auto-generated method stub
				Collections.sort(circles);
				ManagerFactory.createManager(MyCircleBean.class).saveList(
						circles);
			}
			
		});
	}

	@Override
	public String[] getTabTitles() {
		// TODO Auto-generated method stub
		return mTabTitles;
	}

	@Override
	protected boolean showHomeAsUp() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean enalbleTabAnimator() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void setTabAnimatorImage(ImageView iv) {
		// TODO Auto-generated method stub
		super.setTabAnimatorImage(iv);
		// iv.setBackgroundResource(R.drawable.tab_animator);
	}

	@Override
	public Class<? extends Fragment>[] getFragments() {
		// TODO Auto-generated method stub
		/*return (Class<? extends Fragment>[]) new Class<?>[] {
				SuperFriendsFragment.class, SuperFriendsFragment.class,
				SuperFriendsFragment.class, SuperFriendsFragment.class,
				SuperFriendsFragment.class };*/
		/*return (Class<? extends Fragment>[]) new Class<?>[] {
				RecentCallFragment.class, RecentCallFragment.class,
				RecentCallFragment.class, RecentCallFragment.class,
				RecentCallFragment.class };*/
		/*return (Class<? extends Fragment>[]) new Class<?>[] {
				ShareFragment.class, ShareFragment.class,
				ShareFragment.class, ShareFragment.class,
				ShareFragment.class };*/
		
		return (Class<? extends Fragment>[]) new Class<?>[] {
				RecentCallFragment.class, RecentChatListFragment.class, SuperFriendsFragment.class, 
				ExploreFragment.class, 
				MineFragment.class };
		
	}

	/**
	 * 切换拨号面板可见性
	 * 
	 * @author 洋
	 * 
	 */
	public static interface DialPadSwitch {
		void toggle();
	}

	/** 小红点 */
	private ImageView mImageViewChatRedDot, mImageViewFriendRedDot;

	@Override
	public View getIndicatorView(int position) {
		// TODO Auto-generated method stub
		if (position == 0) {
			View v = super.getIndicatorView(position);
			TextView tv = ViewHolder.get(v, R.id.title);
			tv.setTextColor(getResources().getColorStateList(R.color.tab_text));
			v.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					int index = mFragmentTabHost.getCurrentTab();
					if (index != 0) {
						return false;
					}
					switch (event.getActionMasked()) {
					case MotionEvent.ACTION_CANCEL:
					case MotionEvent.ACTION_UP:
						Fragment fragment = getSupportFragmentManager()
						.findFragmentByTag(mTabTitles[0]);
						if (fragment instanceof DialPadSwitch) {
							((DialPadSwitch) fragment).toggle();
						}
						break;

					default:
						break;
					}
					return false;
				}
			});
			return v;
		}
		if (position == 1) {
			View v = getLayoutInflater().inflate(
					R.layout.tab_indicator_view_with_red_dot, null);
			TextView tv = ViewHolder.get(v, R.id.title);
			tv.setText(getTabTitles()[position]);
			ImageView iv = ViewHolder.get(v, R.id.icon);
			iv.setImageResource(getTabIcons()[position]);
			mImageViewChatRedDot = ViewHolder.get(v, R.id.red_dot);
			mImageViewChatRedDot.setVisibility(View.GONE);
			tv.setTextColor(getResources().getColorStateList(R.color.tab_text));
			return v;
		}
		if (position == 2) {
			View v = getLayoutInflater().inflate(
					R.layout.tab_indicator_view_with_red_dot, null);
			TextView tv = ViewHolder.get(v, R.id.title);
			tv.setText(getTabTitles()[position]);
			ImageView iv = ViewHolder.get(v, R.id.icon);
			iv.setImageResource(getTabIcons()[position]);
			mImageViewFriendRedDot = ViewHolder.get(v, R.id.red_dot);
			mImageViewFriendRedDot.setVisibility(View.GONE);
			tv.setTextColor(getResources().getColorStateList(R.color.tab_text));
			return v;
		}
		View v = super.getIndicatorView(position);
		TextView tv = ViewHolder.get(v, R.id.title);
		tv.setTextColor(getResources().getColorStateList(R.color.tab_text));
		return v;
	}

	@Override
	public Bundle getFragmentArguments(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int[] getTabIcons() {
		// TODO Auto-generated method stub
		return new int[] { R.drawable.tab1, R.drawable.tab2, R.drawable.tab3,
				R.drawable.tab4, R.drawable.tab5 };
	}

	@Override
	public void onTabChanged(String tabId) {
		// TODO Auto-generated method stub
		super.onTabChanged(tabId);
		int index = mFragmentTabHost.getCurrentTab();
		if (index == 1) {
			mImageViewChatRedDot.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mMessageReceiver);
		unbindService(mServiceConnection);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (Constants.ACTION_RECEIVE_MSG.equals(action)) {
				int index = mFragmentTabHost.getCurrentTab();
				if (index != 1) {
					mImageViewChatRedDot.setVisibility(View.VISIBLE);
				}
				Fragment fragment = getSupportFragmentManager()
						.findFragmentByTag(mTabTitles[1]);
				if (fragment != null && fragment instanceof MessageAccessable) {
					((MessageAccessable) fragment).refreshMessage();
				}
			}
		}

	}

	/** 腾讯分享回调接口 */
	public static IUiListener qZoneShareListener = new IUiListener() {

		@Override
		public void onCancel() {
		}

		@Override
		public void onError(UiError e) {
			// TODO Auto-generated method stub
			System.out.println("MainActivity.enclosing_method()"
					+ e.errorMessage);
		}

		@Override
		public void onComplete(Object response) {
			// TODO Auto-generated method stub
			System.out.println("MainActivity.enclosing_method()"
					+ response.toString());
		}

	};
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == com.tencent.connect.common.Constants.REQUEST_QZONE_SHARE) {
			if (resultCode == com.tencent.connect.common.Constants.ACTIVITY_OK) {
				Tencent.handleResultData(data, qZoneShareListener);// 腾讯分享接口
			}
		}
	}
}
